package com.rykj.qxj.monitor.core;

import com.rykj.qxj.server.model.entity.Apply;
import com.rykj.qxj.server.model.entity.DataCount;
import com.rykj.qxj.server.model.entity.DataCountApp;
import com.rykj.qxj.server.services.IApiManageService;
import com.rykj.qxj.server.services.IApplyManageService;
import com.rykj.qxj.server.services.IDataCountService;
import com.rykj.qxj.server.util.date.DateUtils;
import com.techindata.cacheredis.CacheGet;
import com.techindata.cacheredis.CacheZSet;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 每天统计
 */
@Component
@Log4j
public class PageViewHandle {

    @Autowired
    private IApiManageService apiManageService;
    @Autowired
    private IDataCountService dataCountService;
    @Autowired
    private IApplyManageService applyManageService;
    private static final String PER_APPLICATION_VISITCOUNT_TODAY= "perApplicationVisitCount_today";
    @Scheduled(cron = "0 10 1 * * ?")
    public void statisPageView(){
        log.info("开始每天访问量统计=========");
        String nowDate = DateUtils.getDate(DateUtils.addHowDay(new Date(),-1),"yyyy-MM-dd");
//        String nowDate = DateUtils.getDate(new Date(),"yyyy-MM-dd");
         //统计当天的接口访问量
        statisApiDataByDay(nowDate);
        log.info("统计当天的接口访问量=========end");
        //统计当天的应用的访问量
        statisAppDataByDay(nowDate);
        log.info("统计当天的应用的访问量=========end");

    }

    private void statisApiDataByDay(String nowDate){
        try {
            List<DataCount> dataCounts = new ArrayList<>();
            DataCount dataCount = null;

            List<Map<String,Object>> apiManages =apiManageService.findAllApi();  //获取所有审核通过的接口列表
            for(Map<String,Object> map : apiManages){
                String appKey = (String) map.get("applyKey");
                try {
                    String url = (String) map.get("url");
                    if(url!=null){
                        String member = url.replaceAll("/",":").replaceFirst(":","");
                        Long val = 0L;
                        String key = "perApiVisitCount_" +appKey+ "_today" + ":" + nowDate;
                        if (CacheZSet.zscore(key, member) != -1) {
                            val = new Double(CacheZSet.zscore(key, member)).longValue();
                        }
                        dataCount = new DataCount();
                        dataCount.setCatalogId(Integer.valueOf(map.get("api_type_id").toString()));
                        dataCount.setApplyId(Integer.valueOf(map.get("id").toString()));
                        dataCount.setCountType(map.get("api_type").toString());
                        dataCount.setApiId(Integer.valueOf(map.get("apiId").toString()));
                        dataCount.setCountNum(val);
                        dataCount.setCountDate(DateUtils.addHowDay(new Date(),-1));
                        dataCount.setCreatedTime(new Date());
                        dataCounts.add(dataCount);
                    }
                }catch (Exception e){
                    log.error("接口每日访问量统计异常,appKey:" + appKey,e);
                }
            }
            dataCountService.saveBatchDataCount(dataCounts);
        } catch (Exception e) {
            log.error("访问量统计异常",e);
        }
    }

    private void statisAppDataByDay(String nowDate){
        try {
            List<DataCountApp> dataAppCounts = new ArrayList<>();
            DataCountApp dataAppCount = null;
            List<Apply> apiManages =applyManageService.findAllApplys();  //获取所有审核通过的接口列表
            for(Apply apply : apiManages){
                try {
                    String appKey = apply.getApplyKey();
                    if(appKey!=null){
                        String member = appKey;
                        Long val = 0l;
                        String key = PER_APPLICATION_VISITCOUNT_TODAY +  ":" + nowDate;
                        if (CacheZSet.zscore(key,member) != -1) {
                            val = new Double(CacheZSet.zscore(key, member)).longValue();
                        }
                        dataAppCount = new DataCountApp();
                        dataAppCount.setApplyId(apply.getId());
                        dataAppCount.setCatalogId(apply.getCategoryId());
                        dataAppCount.setCountNum(val);
                        dataAppCount.setCountDate(DateUtils.addHowDay(new Date(),-1));
                        dataAppCount.setCreatedTime(new Date());
                        dataAppCounts.add(dataAppCount);
                    }
                }catch (Exception e){
                    log.error("应用每日访问量统计异常,appId:" + apply.getId(),e);
                }
            }
            dataCountService.saveBatchDataAppCount(dataAppCounts);
        } catch (Exception e) {
            log.error("应用访问量统计异常",e);
        }
    }

    public static void main(String[] args) {

        System.out.println(CacheGet.getObject("data-api:websterApp:testPrams:2019-05-07"));
    }
}
